<template>
  <div class="login-container">
    <div class="video-bg">
      <video class="video" muted="muted" autoplay="autoplay" loop>
        <source src="../../assets/video/login-bg.mp4" type="video/mp4" />
      </video>
    </div>
    <!-- 登录框 -->
    <div class="login-box">
      <div v-if="!forgetPasswordState">
        <div class="tabs-box">
          <div @click="tabChange('0')" :class="tab == '0' ? 'on' : ''">
            登录
          </div>
          <div @click="tabChange('1')" :class="tab == '1' ? 'on' : ''">
            注册
          </div>
        </div>
        <!-- 登录 -->
        <el-form
          ref="loginForm"
          :model="loginForm"
          :rules="loginRules"
          class="login-form"
          auto-complete="on"
          label-position="left"
          v-if="tab == 0"
        >
          <!-- 用户名 -->
          <el-form-item prop="username">
            <el-input
              ref="username"
              v-model="loginForm.username"
              placeholder="用户名"
              name="username"
              type="text"
              clearable
            />
          </el-form-item>

          <!-- 密码 -->
          <el-form-item prop="password">
            <el-input
              ref="password"
              v-model="loginForm.password"
              clearable
              show-password
              placeholder="密码"
              name="password"
              @keyup.enter.native="handleLogin"
            />
          </el-form-item>

          <!-- 登录验证码 -->
          <el-form-item prop="loginCode" class="code-form">
            <el-input
              ref="codeNum"
              v-model="loginForm.code"
              type="text"
              placeholder="验证码"
              @keyup.enter.native="handleLogin"
            />
            <div class="code-box">
              <img
                :src="captcha.data"
                alt="图形验证码"
                @click="handleCaptcha"
              />
            </div>
          </el-form-item>

          <el-button
            class="login-button"
            :loading="loading"
            type="primary"
            @click.native.prevent="handleLogin"
            >登录
          </el-button>

          <div class="forget-password">
            <span @click="onForgetPassword(true)">忘记密码</span>
          </div>
        </el-form>

        <!-- 注册 -->
        <el-form
          ref="registerForm"
          :model="registerForm"
          :rules="registerRules"
          class="login-form"
          auto-complete="on"
          label-position="left"
          v-else
        >
          <!-- 用户名 -->
          <el-form-item prop="username">
            <el-input
              v-model="registerForm.username"
              placeholder="用户名"
              name="username"
              type="text"
              clearable
            />
          </el-form-item>

          <!-- 密码 -->
          <el-form-item prop="password">
            <el-input
              v-model="registerForm.password"
              clearable
              show-password
              placeholder="密码"
              name="password"
              @keyup.enter.native="handleLogin"
            />
          </el-form-item>

          <!-- 确认密码 -->
          <el-form-item prop="passwordCheck">
            <el-input
              v-model="registerForm.passwordCheck"
              clearable
              show-password
              placeholder="确认密码"
              name="password"
              @keyup.enter.native="handleRegister"
            />
          </el-form-item>

          <!-- 手机号 -->
          <el-form-item prop="phone">
            <el-input
              v-model="registerForm.phone"
              placeholder="手机号"
              name="phone"
              type="text"
              @keyup.enter.native="handleRegister"
              clearable
            />
          </el-form-item>

          <!-- 注册验证码 -->
          <el-form-item prop="registerCode" class="code-form">
            <el-input
              v-model="registerForm.code"
              type="text"
              placeholder="验证码"
              @keyup.enter.native="handleRegister"
            />
            <div class="code-box">
              <div class="phone">
                <button :class="getCodeShow ? 'on' : ''" @click="getCode()">
                  {{ codeText }}
                </button>
              </div>
            </div>
          </el-form-item>

          <el-button
            class="login-button"
            :loading="loading"
            type="primary"
            @click.native.prevent="handleRegister"
            >注册
          </el-button>
        </el-form>
      </div>

      <!-- 忘记密码 -->
      <div v-else>
        <div class="tabs-box">
          <div class="on">重设密码</div>
        </div>
        <!-- 注册 -->
        <el-form
          ref="forgetPassword"
          :model="forgetPasswordForm"
          :rules="forgetPasswordRules"
          class="login-form"
          auto-complete="on"
          label-position="left"
        >
          <!-- 手机号 -->
          <el-form-item prop="phone">
            <el-input
              v-model="forgetPasswordForm.phone"
              placeholder="手机号"
              name="phone"
              type="text"
              @keyup.enter.native="handleRegister"
              clearable
            />
          </el-form-item>

          <!-- 注册验证码 -->
          <el-form-item prop="registerCode" class="code-form">
            <el-input
              v-model="forgetPasswordForm.code"
              type="text"
              placeholder="验证码"
              @keyup.enter.native="handleRegister"
            />
            <div class="code-box">
              <div class="phone">
                <button :class="getCodeShow ? 'on' : ''" @click="getCode()">
                  {{ codeText }}
                </button>
              </div>
            </div>
          </el-form-item>

          <!-- 新密码 -->
          <el-form-item prop="password">
            <el-input
              v-model="forgetPasswordForm.password"
              clearable
              show-password
              placeholder="新密码"
              name="password"
              @keyup.enter.native="handleLogin"
            />
          </el-form-item>

          <!-- 确认新密码 -->
          <el-form-item prop="passwordCheck">
            <el-input
              v-model="forgetPasswordForm.passwordCheck"
              clearable
              show-password
              placeholder="确认新密码"
              name="password"
              @keyup.enter.native="handleRegister"
            />
          </el-form-item>

          <el-button
            class="login-button"
            :loading="loading"
            type="primary"
            @click.native.prevent="handleRegister"
            >提交
          </el-button>

          <div class="forget-password">
            <span @click="onForgetPassword(false)">返回登录</span>
          </div>
        </el-form>
      </div>
    </div>

    <!-- 底部 -->
    <footer>
      <span>牛利智能物联科技（杭州）有限公司</span>
      <a href="https://beian.miit.gov.cn/#/Integrated/index" target="_blank"
        >浙ICP备2020034886号-2</a
      >
      <i></i>
    </footer>
  </div>
</template>

<script>
// import { validUsername } from "@/utils/validate";

import { validUsername } from "@/utils/validate";
import { getCaptcha } from "@/api/auth";

export default {
  name: "Login",
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error("Please enter the correct user name"));
      } else {
        callback();
      }
    };
    const validatePassword = (rule, value, callback) => {
      if (value.length < 1) {
        callback(new Error("The password can not be less than 1 digits"));
      } else {
        callback();
      }
    };
    return {
      tab: "0",
      // 登录
      captcha: {},
      loginForm: {
        username: "",
        password: "",
        grant_type: "password",
        captchaId: "",
        code: "",
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", validator: validateUsername },
        ],
        password: [
          { required: true, trigger: "blur", validator: validatePassword },
        ],
      },
      passwordType: "password",
      // 注册
      registerForm: {
        username: "",
        password: "",
        phone: "",
        code: "",
      },
      registerRules: {},

      // 忘记密码
      forgetPasswordForm: {
        username: "",
        password: "",
        phone: "",
        code: "",
        passwordCheck: "",
      },
      forgetPasswordRules: {},
      forgetPasswordState: false,

      loading: false,
      redirect: undefined,

      codeText: "获取验证码",
      countdown: 60, //倒计时
      getCodeShow: false, //显示倒计时
    };
  },
  created() {
    this.handleCaptcha();
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
  },
  methods: {
    /**
     * 登录、注册切换
     */
    tabChange(val) {
      this.tab = val;
    },
    /**
     * 获取验证码
     */
    handleCaptcha() {
      getCaptcha().then((res) => {
        res.data.data = `data:image/png;base64,${res.data.data}`;
        this.captcha = res.data;
      });
    },
    /**
     * 登录
     */
    handleLogin() {
      // 二维码id
      this.loginForm.captchaId = this.captcha.id;
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.$store
            .dispatch("tenant/login", this.loginForm)
            .then((res) => {
              if (res.code === 0) {
                // this.$store.dispatch("tenant/getInAuth");
                // this.$store.dispatch("menu/getLayoutInAuth");
                this.loading = false;
                this.$router.push({ path: this.redirect || "/" });
              }
            })
            .catch((err) => {
              this.loading = false;
              console.log(err);
            });
        } else {
          console.log("表单校验失败");
        }
      });
    },
    LoginByUsername({ commit }, userInfo) {
      console.log(commit);
      const username = userInfo.username.trim();
      return new Promise((resolve, reject) => {
        loginByUsername(username, userInfo.password)
          .then((response) => {
            const data = response.data;
            Cookies.set("Token", response.data.token); //登录成功后将token存储在cookie之中
            commit("SET_TOKEN", data.token);
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    /**
     * 忘记密码
     */
    onForgetPassword(state) {
      this.forgetPasswordState = state;
    },
  },
};
</script>

<style lang="scss">
$light_gray: #fff;
$dark_gray: #424446;
$cursor: #fff;

.login-container {
  width: 100%;
  min-height: 100%;
  background-color: #414141;

  /* 登录video背景 */
  .video-bg {
    width: 100%;
    height: calc(100vh - 20px);
    position: relative;
    background-color: #02000a;

    .video {
      width: 100%;
      position: absolute;
      left: 0;
      bottom: -20px;
    }
  }

  /* 登录框 */
  .login-box {
    position: fixed;
    background: rgba($color: #ffffff, $alpha: 0.65);
    z-index: 9;
    width: 400px;
    padding: 20px 20px 15px;
    right: 10%;
    top: 50%;
    transform: translate(0%, -50%);
    box-shadow: 0 12px 24px 0 rgba(28, 31, 33, 0.1);
    transition: all 0.2s;

    /* tab切换 */
    .tabs-box {
      width: calc(100% - 2px);
      margin: 0 auto;
      display: flex;
      border-bottom: 1px solid #f2f2f2;
      margin-bottom: 20px;
      justify-content: center;

      div {
        padding: 10px 28px;
        margin: 0 16px;
        border-bottom: 2px solid transparent;
        cursor: pointer;
        user-select: none;
        font-size: 22px;
        color: #676b81;
      }

      .on {
        color: var(--theme-color);
        border-bottom: 2px solid var(--theme-color);
      }
    }

    /* 输入框 */
    .login-form {
      .el-input {
        display: inline-block;
        height: 40px;
        width: 100%;

        input {
          -webkit-appearance: none;
          border-radius: 0px;
          padding: 12px 5px 12px 15px;
          height: 40px;
        }

        input:-webkit-autofill {
          transition: background-color 5000s ease-in-out 0s;
        }
      }

      .svg-container {
        color: $dark_gray;
        width: 30px;
        display: inline-block;
        position: absolute;
        z-index: 8;
      }

      .show-pwd {
        position: absolute;
        right: 10px;
        font-size: 16px;
        color: #b0a5a5;
        cursor: pointer;
        user-select: none;
      }
    }

    /* 验证码 */
    .code-form {
      .el-form-item__content {
        display: flex;
        align-items: center;
      }

      .code-box {
        width: 140px;
        height: 40px;
        margin-left: 16px;

        .phone {
          width: 100%;
          height: 100%;

          button {
            width: 100%;
            height: 100%;
            font-size: 14px;
            color: #ffffff;
            background-color: var(--theme-color);
            cursor: pointer;
            border: none;
            line-height: 0;
          }

          button:focus {
            outline: none;
          }

          .on {
            opacity: 0.6;
          }
        }
      }
    }

    /* 登录按钮 */
    .login-button {
      width: 100%;
    }

    .forget-password {
      display: flex;
      padding: 16px 0 4px;
      justify-content: flex-end;

      span {
        font-size: 14px;
        color: var(--theme-color);
        height: 16px;
        box-sizing: border-box;
        cursor: pointer;
      }

      span:hover {
        border-bottom: 1px solid var(--theme-color);
      }
    }
  }

  /* 底部 */
  footer {
    width: 100%;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-top: 1px solid rgba(200, 200, 200, 0.3);
    background-color: rgba(200, 200, 200, 0.3);
    position: fixed;
    z-index: 2;
    bottom: 0;
    left: 0;

    span {
      color: #f9f9f9;
      font-weight: bold;
      font-size: 12px;
      margin-right: 8px;
    }

    a {
      font-size: 12px;
      color: #bbbbbb;
      margin-right: 4px;
    }

    i {
      width: 20px;
      height: 20px;
      background-image: url(../../assets/emblem.png);
      background-size: 100% 100%;
      background-repeat: no-repeat;
    }
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.login-container2 {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;

  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}
</style>
